package com.bot.adms.controller.apply;

import com.alibaba.fastjson2.JSONObject;
import com.bot.adms.service.IApplyService;
import com.bot.adms.service.impl.ApplyServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 服务端 servlet 用于处理投放申请提交的业务
 */
@WebServlet("/apply/submit.do")
public class SubmitApplyServlet extends HttpServlet {
    IApplyService applyService = new ApplyServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码和响应格式
        req.setCharacterEncoding("UTF-8");
        //设置响应的内容类型为JSON格式，字符编码为UTF-8，告知客户端响应数据的格式和编码
        resp.setContentType("application/json;charset=UTF-8");

        //响应体创建
        JSONObject jsonObject = new JSONObject();
        //success定义【true成功，false失败】
        boolean success = false;
        //响应码定义【响应码,200-成功,500-失败】
        int code = 500;

        //1.接收参数
        String idStr = req.getParameter("id");
        //提交操作固定设置状态为待审核(2)，
        Integer status = 2;

        if (idStr == null || idStr.trim().isEmpty()) {
            jsonObject.put("msg", "投放申请ID不能为空");
            ServletOutputStream out = resp.getOutputStream();
            out.write(jsonObject.toString().getBytes("UTF-8"));
            out.flush();
            out.close();
            return;
        }

        try {
            //2.转换ID类型
            Long applyId = Long.parseLong(idStr.trim());

            //3.调用提交业务接口
            Boolean result = applyService.submitApply(applyId, status);
            if (result) {
                success = true;
                code = 200;
                jsonObject.put("msg", "提交投放申请成功");
            } else {
                jsonObject.put("msg", "提交投放申请失败");
            }

        } catch (NumberFormatException e) {
            //ID格式错误
            jsonObject.put("msg", "ID格式错误，请传入有效的数字");
        } catch (IllegalArgumentException e) {
            //业务验证异常
            jsonObject.put("msg", e.getMessage());
        } catch (Exception e) {
            //其他异常
            jsonObject.put("msg", "提交投放申请异常：" + e.getMessage());
        }

        //设置公共响应字段
        jsonObject.put("success", success);
        jsonObject.put("code", code);

        //4.响应数据
        ServletOutputStream out = resp.getOutputStream();
        out.write(jsonObject.toString().getBytes("UTF-8"));
        out.flush();
        out.close();
    }


}
